﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;

using DNA;
using TJADRICD.CollaborativeDesignPlugin.Form;
using TJADRICD.CollaborativeDesignPlugin.Function;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using DBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;


namespace TJADRICD.CollaborativeDesignPlugin.Form
{
    public partial class SignControl : System.Windows.Forms.Form
    {

        public SignControl()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }

        string signer;

        struct Pair
        {
            public string fileName;
            public FileStream fs;
            public Pair(string fileName, FileStream fs)
            {
                this.fileName = fileName;
                this.fs = fs;
            }
        }
        List<Pair> locks = new List<Pair>();


        private void SignControl_Load(object sender, EventArgs e)
        {
            foreach (string webPath in Config.ProjectPath)
            {
                /*                MessageBox.Show(webPath);*/
                DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
                DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
                foreach (DirectoryInfo Dir_Pro in Dir_Pros)
                {
                    if ((Dir_Pro.Name == "Sign") || (Dir_Pro.Name == "TK"))
                    {
                        continue;
                    }
                    this.cb_ProNo.Items.Add(Dir_Pro.Name);
                }
            }

            bool flag = false;
            try
            {
               signer = null;
               StringBuilder name = new StringBuilder(1024);
               OpenFileDialog ofd = new OpenFileDialog();
               ofd.InitialDirectory = Config.HandwritingPath;
               ofd.Filter = "签名验证文件 (*.vrf)|*.vrf|所有文件|*.*";
               ofd.FilterIndex = 1;

               if (ofd.ShowDialog() == DialogResult.OK)
               {
                   int status = -3;
                   status = Function_Verify.TJAD_SIGN_ReadName(ofd.FileName, name);
                   if (status == 0)
                   {
                       signer = name.ToString();
                       Tools.WriteMessageWithReturn("签名人:" + signer);

                       lblSigner.Text = signer;
                       flag = true;
                   }
                   else
                   {
                       MessageBox.Show("读取VRF文件" + ofd.FileName + "失败" + "   出错编号" + status.ToString());
                   }
               }
             //  else
             //  {
                   //MessageBox.Show("读取失败2");
            //   }
//                int status = TJAD_iKey_ReadName(name);
//                Tools.WriteMessageWithReturn(status.ToString());
//                if (status == 0)
//                {
//                    signer = name.ToString();
//                    Tools.WriteMessageWithReturn("签名人:" + signer);
// 
//                    lblSigner.Text = signer;
//                    flag = true;
//                }
//                else
//                {
//                    
//                }
               //signer = "李刚";
                


            }
            catch(System.Exception ex)
            {
                MessageBox.Show("读取用户文件发生异常"+ex.Message+ex.StackTrace);
            }
            if (!flag)
            {
                this.Close();
            }
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            UnLockAllFiles();
            try
            {
                if (signer == null)
                {
                    //MessageBox.Show("请选择签名者！");
                    //btnSelectSigner.PerformClick();
                    if (signer == null)
                        return;
                }
                Editor ed = Tools.Editor;
                for (int i = 0; i < dataGridView.Rows.Count; i++)
                {
                    DataGridViewRow row = dataGridView.Rows[i];
                    bool needSign = false;
                    bool needUnsign = false;
                    List<string> signItems = new List<string>();
                    List<string> unsignItems = new List<string>();
                    int approvedByIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["ApprovedBy"]);
                    int ELV3Index = dataGridView.Columns.IndexOf(dataGridView.Columns["ELV3"]);
                    int CTBIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["CTB"]);
                    for (int j = approvedByIndex; j <= ELV3Index; j++)
                    {
                        if (j == CTBIndex)
                        {
                            continue;
                        }
                        DataGridViewCell cell = row.Cells[j];
                        if (row.Cells[j].FormattedValue.ToString() != ""
                            && row.Cells[j].Style.BackColor == Color.LightGreen
                            && row.Cells[j].Value.ToString() == signer)
                        {
                            signItems.Add(dataGridView.Columns[j].Name);
                            needSign = true;
                        }
                        if (row.Cells[j].Value.ToString() == ""
                            && row.Cells[j].Style.BackColor == Color.LightGreen)
                        {
                            unsignItems.Add(dataGridView.Columns[j].Name);
                            needUnsign = true;
                        }
                    }
                    if (needSign || needUnsign)
                    {
                        string fileName = dataGridView.Rows[i].Cells["FileName"].Value.ToString();
                        Database db = new Database(false, true);
                        db.ReadDwgFile(fileName,
                            System.IO.FileShare.ReadWrite,
                            false,
                            "");
                        ed.WriteMessage("正在对 " + row.Cells["SheetTitle"].Value.ToString() + " 签名...\n");
                        CommandSign.SignDB(db, signer, signItems, checkBox1.Checked);
                        ed.WriteMessage("正在对 " + row.Cells["SheetTitle"].Value.ToString() + " 删除签名...\n");
                        CommandSign.UnsignDB(db, unsignItems);
                        db.SaveAs(fileName, DwgVersion.Current);
                        CommandSign.PublishFile(fileName);
                    }
                    ed.WriteMessage("对 " + row.Cells["SheetTitle"].Value.ToString() + " 的操作完成！\n");
                }
                MessageBox.Show("完成！");
                ed.WriteMessage("全部签名完成！\n");
            }
            catch(System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Close();
            }
        }

        private void btnAddFile_Click(object sender, EventArgs e)
        {
//            string path = "";
//            ProjectChooseForm pcf = new ProjectChooseForm(ref path, false);
//            pcf.ShowDialog();
            if (this.cb_SubProNo.Text != "")
            {
                OpenFileDialog ofd = new OpenFileDialog();
                string dir = CommandSign.makeSubProDir(this.cb_ProNo.Text, this.cb_SubProNo.Text, this.cb_Major.Text);

                if (!(new DirectoryInfo(dir)).Exists)
                {
                    MessageBox.Show("目录不存在!");
                    return;
                }
                ofd.InitialDirectory = dir;
/*                MessageBox.Show(CommandSign.path);*/
                ofd.Filter = "Drawing(*.dwg)|*.dwg";
                ofd.Multiselect = true;
                DialogResult dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    int count = 0;
                    foreach (string fileName in ofd.FileNames)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            ++count;
                        }
                    }
                    this.progressBar1.Visible = true;
                    this.progressBar1.Maximum = count;
                    count = 0;
                    foreach (string file in ofd.FileNames)
                    {
                        if (AddFile(file))
                        {
                            LockFile(file);
                        }
                        this.progressBar1.Increment(++count);
                    }
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                    MessageBox.Show("导入完成!");
                    this.progressBar1.Visible = false;
                }
                //                 Editor ed = Tools.Editor;
                //                 PromptOpenFileOptions opts = new PromptOpenFileOptions("选择待签名文件");
                //                 opts.InitialDirectory = CommandSign.path;
                //                 opts.Filter = "Dwawing(*.dwg)|*.dwg";
                //                 PromptFileNameResult pr = ed.GetFileNameForOpen(opts);
                //                 if (pr.Status == PromptStatus.OK)
                //                 {
                //                     AddFile(pr.StringResult);
                //                     LockFile(pr.StringResult);
                //                 }
            }
            else
            {
                MessageBox.Show("未选择项目或子项目！");
            }
        }

        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            try
            {
 //               string path = "";
 //               ProjectChooseForm pcf = new ProjectChooseForm(ref path, false);
//                pcf.ShowDialog();
                //                 MessageBox.Show(CommandSign.path);
                //                 FolderDialog fd = new FolderDialog();
                //                 DialogResult dr = fd.DisplayDialog();

                if (this.cb_SubProNo.Text != "")
                {
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    string rootFolderPath = CommandSign.makeSubProDir(this.cb_ProNo.Text, this.cb_SubProNo.Text, this.cb_Major.Text);

                    if (!(new DirectoryInfo(rootFolderPath)).Exists)
                    {
                        MessageBox.Show("目录不存在!");
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        return;
                    }
                    List<string> files = new List<string>();
                    CommandSign.GoThroughDirectory(rootFolderPath, ref files);
                    int count = 0;
                    foreach (string fileName in files)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            ++ count;
                        }
                    }
                    this.progressBar1.Visible = true;
                    this.progressBar1.Maximum = count;
                    count = 0;
                    foreach (string fileName in files)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            if (AddFile(fileName))
                            {
                                LockFile(fileName);
                            }
                            this.progressBar1.Increment(++count);
                        }
                    }
                    MessageBox.Show("导入完成!");
                    this.progressBar1.Visible = false;
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                }
                else
                {
                    MessageBox.Show("未选择项目或子项目！");
                }
            }
            catch(System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        /// <summary>
        /// 加锁
        /// </summary>
        /// <param name="fileName"></param>
        private void LockFile(string fileName)
        {
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                locks.Add(new Pair(fileName, fs));
            }
            catch
            {
                MessageBox.Show(fileName + "正被打开，不能操作，已被跳过。");
            }
        }
        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="fileName"></param>
        private void UnLockFile(string fileName)
        {
            try
            {
                foreach (Pair p in locks)
                {
                    if (p.fileName == fileName)
                    {
                        p.fs.Close();
                        break;
                    }
                }
            }
            catch
            {
                MessageBox.Show(fileName + "在解锁文件时发生异常");
            }
        }


        private string GetAttributeByPosition(Database db, Point3d position)
        {
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable table = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                foreach (ObjectId recorfId in table)
                {
                    BlockTableRecord record = trans.GetObject(recorfId, OpenMode.ForRead) as BlockTableRecord;
                    if (CommandFrame.IsVersionType(record.Name))
                    {
                        ObjectIdCollection RefIds = record.GetBlockReferenceIds(true, true);
                        foreach (ObjectId RefId in RefIds)
                        {
                            BlockReference Reference = trans.GetObject(RefId, OpenMode.ForRead) as BlockReference;
                            AttributeCollection RefAttrisId = Reference.AttributeCollection;
                            foreach (ObjectId AttriId in RefAttrisId)
                            {
                                AttributeReference AttriRef = trans.GetObject(AttriId, OpenMode.ForRead) as AttributeReference;
                                if (AttriRef.Tag.EndsWith("SignPos") && (AttriRef.Position == position))
                                {
                                    return AttriRef.Tag.Substring(0, AttriRef.Tag.Length - "SignPos".Length);
                                }
                            }
                        }
                    }
                }
                return "";
            }
        }
        
        /// <summary>
        /// 解锁所有文件
        /// </summary>
        private void UnLockAllFiles()
        {
            for(int i=0; i<dataGridView.Rows.Count; i++)
            {
                UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
            }
        }
        
        /// <summary>
        /// 在datagridview控件里加入文件
        /// </summary>
        /// <param name="fileName"></param>
        public bool AddFile(string fileName)
        {
            if (signer == null)
            {
                //MessageBox.Show("请选择签名者！");
                //btnSelectSigner.PerformClick();
                if (signer == null)
                    return false;
            }
            try
            {
                Editor ed = Tools.Editor;
                //如果已经添加过此文件，无视
                foreach(DataGridViewRow row in dataGridView.Rows)
                {
                    string oldFileName = row.Cells["FileName"].Value.ToString();
                    if (oldFileName == fileName)
                    {
//                        MessageBox.Show(oldFileName + "已添加过，跳过！");
                        return false;
                    }
                    int oldLength = oldFileName.Length;
                    int newLength = fileName.Length;
                    if (oldFileName.Substring(0, oldLength - 5) == fileName.Substring(0, newLength - 5))
                    {
                        if (oldFileName[oldLength - 5] >= fileName[newLength - 5])
                        {
                            //                        MessageBox.Show(fileName + "版本过低，跳过");
                            return false;
                        }
                        if (oldFileName[oldLength - 5] < fileName[newLength - 5])
                        {
                            UnLockFile(row.Cells["FileName"].Value.ToString());
                            dataGridView.Rows.Remove(row);
                            break;
                        }
                    }
                }

                //对于此文件，找到其中的图框并加入
                using(Database db = new Database(false, true))
                {
                    db.ReadDwgFile(fileName,
                        System.IO.FileShare.ReadWrite,
                        false,
                        "");

                    String strDbHashCode = Function_Hash.GetDwgHash(db);
                    int SuccessCount = 0;
                    int FailCount = 0;

                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        foreach (ObjectId blockid in bt)
                        {
                            BlockTableRecord record = trans.GetObject(blockid, OpenMode.ForRead) as BlockTableRecord;
                            ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(false, false);
                            foreach (ObjectId blockRefId in blockRefIds)
                            {
                                BlockReference blockRef = trans.GetObject(blockRefId, OpenMode.ForRead) as BlockReference;
                                Entity ent = trans.GetObject(blockRefId, OpenMode.ForRead) as Entity;
                                bool flag = true;
                                try
                                {
                                    Extents3d ext = blockRef.GeometricExtents;
                                }
                                catch
                                {
                                    flag = false;
                                }
                                if (flag)
                                {
                                    //Tools.WriteMessageWithReturn("Success Geo"+" Name=" + blockRef.Name+" BlockName=" + ent.BlockName);
                                    SuccessCount++;
                                }
                                else
                                {
                                    //Tools.WriteMessageWithReturn("Fail Geo" + " Name=" + blockRef.Name + " BlockName=" + ent.BlockName);
                                    FailCount++;
                                }
                            }
                        }
                        trans.Commit();
                    }
                    //Tools.WriteMessageWithReturn("Success=" + SuccessCount.ToString() + " Fail=" + FailCount.ToString());
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        BlockTable table = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = trans.GetObject(table[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                        //先找到所有的签名块，取得它们的位置，方便后面检索哪些栏目已经被签过了
                        List<List<Point3d>> possList = new List<List<Point3d>>();
                        List<string> names = new List<string>();
                        List<Point3d> otherposs = new List<Point3d>();//其他人员签名位置

                        List<string> unsignItems = new List<string>();
                        BlockReference brFrame = null;
                        foreach (ObjectId blockId in table)
                        {
                            BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForWrite);
                            if (CommandFrame.IsVersionType(record.Name))
                            {
                                ObjectIdCollection collection = record.GetBlockReferenceIds(true, true);
                                foreach (ObjectId frameId in collection)
                                {
                                    brFrame = trans.GetObject(frameId, OpenMode.ForWrite) as BlockReference;
                                    break;
                                }
                            }
                        }
                        if (brFrame == null)
                        {
                            return false;
                        }
                        if (brFrame.ExtensionDictionary == ObjectId.Null)
                        {
                            Tools.WriteMessageWithReturn("No Dictionary!");
                        }
                        else
                        {
                            DBDictionary dictionary = trans.GetObject(brFrame.ExtensionDictionary, OpenMode.ForRead) as DBDictionary;
                            AttributeCollection ac = brFrame.AttributeCollection;
                            foreach (ObjectId attrId in ac)
                            {
                                AttributeReference signAr = trans.GetObject(attrId, OpenMode.ForWrite) as AttributeReference;
                                if (signAr.Tag.EndsWith("SignPos"))
                                {
                                    string signItem = signAr.Tag.Substring(0, signAr.Tag.Length - "SignPos".Length);
                                    if (!dictionary.Contains(signItem))
                                    {
                                        continue;
                                    }
                                    ObjectId xRecId = dictionary.GetAt(signItem);
                                    Xrecord xRec = trans.GetObject(xRecId, OpenMode.ForRead) as Xrecord;
                                    ResultBuffer data = xRec.Data;
                                    bool flag1 = false, flag2 = false;
                                    string singleMd5 = Function_Hash.GetSingleMD5String(brFrame);
                                    foreach (TypedValue tv in data)
                                    {
                                        if (tv.Value.ToString() == singleMd5)
                                        {
                                            flag1 = true;
                                        }
                                        if (tv.Value.ToString() == strDbHashCode)
                                        {
                                            flag2 = true;
                                        }
                                    }
                                    if (flag1 && flag2)
                                    {
                                        string name = signAr.TextString;
                                        if (name == "hand")
                                        {
                                            foreach (ObjectId idtemp in ac)
                                            {
                                                AttributeReference artemp = trans.GetObject(idtemp, OpenMode.ForWrite) as AttributeReference;
                                                if (artemp.Tag == signItem)
                                                {
                                                    name = artemp.TextString;
                                                }
                                            }
                                        }
                                        int id = names.IndexOf(name);
                                        if (id != -1)
                                        {
                                            possList[id].Add(signAr.Position);
                                        }
                                        else
                                        {
                                            names.Add(name);
                                            List<Point3d> poss = new List<Point3d>();
                                            poss.Add(signAr.Position);
                                            possList.Add(poss);
                                        }
                                    }
                                    else
                                    {
                                        Tools.WriteMessageWithReturn("找到过期签名");
                                        unsignItems.Add(signItem);
                                    }
                                }
                            }
                        }

                        TJADRICD.CollaborativeDesignPlugin.CommandSign.UnsignDB(db, unsignItems);
                        db.SaveAs(db.Filename, DwgVersion.Current);
                        foreach (ObjectId blockId in table)
                        {
                            BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);

                            if (CommandFrame.IsVersionType(record.Name))  //如果此块定义名符合图框块名
                            {
                                ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(true, true);  //取得此块定义所关联的所有块参照Id
                                foreach (ObjectId blockRefId in blockRefIds)
                                {
                                    string sheetTitle = "";
                                    string discipline = "";
                                    string stage = "";
                                    string sheetNo = "";
                                    string rev2 = "";
                                    string ApprovedBy = "";
                                    string ReviewedBy = "";
                                    string CheckedBy = "";
                                    string PrincipalInCharge1 = "";
                                    string PrincipalInCharge2 = "";
                                    string DisciplineResponsible1 = "";
                                    string DisciplineResponsible2 = "";
                                    string DesignedBy1 = "";
                                    string DesignedBy2 = "";
                                    string DrawnBy = "";
                                    string Architecture1 = "";
                                    string Architecture2 = "";
                                    string Architecture3 = "";
                                    string Plumbing1 = "";
                                    string Plumbing2 = "";
                                    string Plumbing3 = "";
                                    string HVAC1 = "";
                                    string HVAC2 = "";
                                    string HVAC3 = "";
                                    string Electricity1 = "";
                                    string Electricity2 = "";
                                    string Electricity3 = "";
                                    string Structure1 = "";
                                    string Structure2 = "";
                                    string Structure3 = "";
                                    string Structure4 = "";
                                    string Structure5 = "";
                                    string Structure6 = "";
                                    string Structure7 = "";
                                    string Power1 = "";
                                    string Power2 = "";
                                    string Power3 = "";
                                    string ELV1 = "";
                                    string ELV2 = "";
                                    string ELV3 = "";

                                    BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead);
                                    AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
                                    foreach (ObjectId attrRefId in blockRefAttrs)
                                    {
                                        AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForWrite);
                                        if (attrRef.Tag == "SheetTitleChinese")
                                        {
                                            sheetTitle = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "DisciplineChinese")
                                        {
                                            discipline = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "StageChinese")
                                        {
                                            stage = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "SheetNo")
                                        {
                                            sheetNo = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "Rev2")
                                        {
                                            rev2 = attrRef.TextString;
                                        }
                                        #region poss
                                        for(int i=0; i<possList.Count; i++)
                                        {
                                            foreach (Point3d pos in possList[i])
                                            {
                                                if (attrRef.Position == pos)
                                                {
                                                    if (attrRef.Tag == "ApprovedBySignPos")
                                                    {
                                                        ApprovedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "ReviewedBySignPos")
                                                    {
                                                        ReviewedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "CheckedBySignPos")
                                                    {
                                                        CheckedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "PrincipalInCharge1SignPos")
                                                    {
                                                        PrincipalInCharge1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "PrincipalInCharge2SignPos")
                                                    {
                                                        PrincipalInCharge2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DisciplineResponsible1SignPos")
                                                    {
                                                        DisciplineResponsible1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DisciplineResponsible2SignPos")
                                                    {
                                                        DisciplineResponsible2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DesignedBy1SignPos")
                                                    {
                                                        DesignedBy1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DesignedBy2SignPos")
                                                    {
                                                        DesignedBy2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DrawnBySignPos")
                                                    {
                                                        DrawnBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "Architecture1SignPos")
                                                    {
                                                        Architecture1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Architecture2SignPos")
                                                    {
                                                        Architecture2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Architecture3SignPos")
                                                    {
                                                        Architecture3 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Plumbing1SignPos")
                                                    {
                                                        Plumbing1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Plumbing2SignPos")
                                                    {
                                                        Plumbing2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Plumbing3SignPos")
                                                    {
                                                        Plumbing3 = names[i];
                                                    }
                                                    if (attrRef.Tag == "HVAC1SignPos")
                                                    {
                                                        HVAC1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "HVAC2SignPos")
                                                    {
                                                        HVAC2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "HVAC3SignPos")
                                                    {
                                                        HVAC3 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Electricity1SignPos")
                                                    {
                                                        Electricity1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Electricity2SignPos")
                                                    {
                                                        Electricity2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Electricity3SignPos")
                                                    {
                                                        Electricity3 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure1SignPos")
                                                    {
                                                        Structure1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure2SignPos")
                                                    {
                                                        Structure2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure3SignPos")
                                                    {
                                                        Structure3 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure4SignPos")
                                                    {
                                                        Structure4 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure5SignPos")
                                                    {
                                                        Structure5 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure6SignPos")
                                                    {
                                                        Structure6 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure7SignPos")
                                                    {
                                                        Structure7 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Power1SignPos")
                                                    {
                                                        Power1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Power2SignPos")
                                                    {
                                                        Power2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Power3SignPos")
                                                    {
                                                        Power3 = names[i];
                                                    }
                                                    if (attrRef.Tag == "ELV1SignPos")
                                                    {
                                                        ELV1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "ELV2SignPos")
                                                    {
                                                        ELV2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "ELV3SignPos")
                                                    {
                                                        ELV3 = names[i];
                                                    }
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                    int temp = dataGridView.Rows.Add(new object[] { false, "查看PDF文件", sheetTitle,
                                                discipline, stage, sheetNo, rev2,
                                                ApprovedBy, ReviewedBy, CheckedBy, PrincipalInCharge1, PrincipalInCharge2, DisciplineResponsible1, DisciplineResponsible2, DesignedBy1, DesignedBy2, DrawnBy,
                                                Architecture1, Architecture2, Architecture3, Plumbing1, Plumbing2, Plumbing3, HVAC1, HVAC2, HVAC3, Electricity1, Electricity2, Electricity3, Structure1, Structure2, Structure3, Structure4, Structure5, Structure6, Structure7, Power1, Power2, Power3, ELV1, ELV2, ELV3
                                                , fileName
                                    });
                                    return true; //只需要第一个图框就够了
                                }
                            }
                        }
                    }

                }
            }
            catch(System.Exception ex)
            {
                Tools.WriteMessageWithReturn(ex.ToString());
            //    Tools.WriteMessageWithReturn("由于文件打开冲突，跳过文件：" + fileName);                
            }
            return false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnExclude_Click(object sender, EventArgs e)
        {
            for(int i=0; i<dataGridView.Rows.Count; i++)
            {
                if(dataGridView.Rows[i].Cells["Operation"].FormattedValue.ToString()=="True")
                {
                    UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
                    dataGridView.Rows.RemoveAt(i);
                    i--;
                }
            }
        }
        #region 选择角色
        private void QuickCheck(string cellName, bool state)
        {
            if (signer == null)
            {
                //MessageBox.Show("请选择签名者！");
                //btnSelectSigner.PerformClick();
                if (signer == null)
                    return;
            }

            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                UpdateCellStatus(i, dataGridView.Columns.IndexOf(dataGridView.Columns[cellName]), state);
            }

        }
        private void cbDrawnBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DrawnBy", ((CheckBox)sender).Checked);
        }

        private void cbApprovedBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ApprovedBy", ((CheckBox)sender).Checked);
        }

        private void cbReviewedBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ReviewedBy", ((CheckBox)sender).Checked);
        }

        private void cbCheckedBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("CheckedBy", ((CheckBox)sender).Checked);
        }

        private void cbPrincipalInCharge1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("PrincipalInCharge1", ((CheckBox)sender).Checked);
        }

        private void cbPrincipalInCharge2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("PrincipalInCharge2", ((CheckBox)sender).Checked);
        }

        private void cbDisciplineResponsible1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DisciplineResponsible1", ((CheckBox)sender).Checked);
        }

        private void cbDisciplineResponsible2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DisciplineResponsible2", ((CheckBox)sender).Checked);
        }

        private void cbDesignedBy1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DesignedBy1", ((CheckBox)sender).Checked);
        }

        private void cbDesignedBy2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DesignedBy2", ((CheckBox)sender).Checked);
        }
        #endregion

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int approvedByIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["ApprovedBy"]);
            int CTBIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["CTB"]);
            if ((e.RowIndex>-1) && (e.ColumnIndex >= approvedByIndex) && (e.ColumnIndex != CTBIndex))
            {
                UpdateCellStatus(e.RowIndex, e.ColumnIndex);
            }
        }
        private void UpdateCellStatus(int row, int col)
        {
            if (signer == null)
            {
                //MessageBox.Show("请选择签名者！");
                //btnSelectSigner.PerformClick();
                if (signer == null)
                    return;
            }
            DataGridViewCell cell = dataGridView.Rows[row].Cells[col];
            cell.Selected = false;
            if(cell.Value.ToString()=="")
            {
                cell.Value = signer;
                cell.Style.BackColor = Color.LightGreen;
            }
            else
            {
                if (!cell.Value.ToString().StartsWith(signer))
                {
                    //已有别人签名，冲突
                    cell.Style.BackColor = Color.Red;
                }
                if (cell.Value.ToString().StartsWith(signer))
                {
                    //是自己的签名，可删
                    cell.Value = "";
                    if (cell.Style.BackColor == Color.LightGreen)
                    {
                        cell.Style.BackColor = Color.Aqua;
                    }
                    else
                    {
                        cell.Style.BackColor = Color.LightGreen;
                    }
                }

            }
        }

        private void UpdateCellStatus(int row, int col, bool status)
        {
            DataGridViewCell cell = dataGridView.Rows[row].Cells[col];
            cell.Selected = false;
            if (status == true)
            {
                //check checkbox
                if (cell.Value.ToString() == "")
                {
                    cell.Value = signer;
                    cell.Style.BackColor = Color.LightGreen;
                }
                if (cell.Value.ToString() != "" && cell.Value.ToString() != signer)
                {
                    //已有别人签名，冲突
                    cell.Style.BackColor = Color.Red;
                }
            }
            else
            {
                //uncheck checkbox
                if (cell.Value.ToString() != "")
                {
                    if (cell.Value.ToString() != signer)
                    {
                        //是别人签的，不应删掉
                        cell.Style.BackColor = Color.LightYellow;
                    }
                    else
                    {
                        //自己签的，可以删掉
                        cell.Style.BackColor = Color.LightGreen;
                        cell.Value = "";
                    }
                }
            }
        }

        private void SignControl_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnLockAllFiles();
        }

        private void cbStructure5_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure5", ((CheckBox)sender).Checked);

        }

        private void cbStructure4_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure4", ((CheckBox)sender).Checked);
        }

        private void cbStructrue6_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure6", ((CheckBox)sender).Checked);
        }

        private void cbArchitecture1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Architecture1", ((CheckBox)sender).Checked);
        }

        private void cbArchitecture2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Architecture2", ((CheckBox)sender).Checked);
        }

        private void cbArchitecture3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Architecture3", ((CheckBox)sender).Checked);
        }

        private void cbStructure1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure1", ((CheckBox)sender).Checked);
        }

        private void cbStructure2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure2", ((CheckBox)sender).Checked);
        }

        private void cbStructure3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure3", ((CheckBox)sender).Checked);
        }

        private void cbStructure7_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure7", ((CheckBox)sender).Checked);
        }

        private void cbPlumbing1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Plumbing1", ((CheckBox)sender).Checked);
        }

        private void cbPlumbing2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Plumbing2", ((CheckBox)sender).Checked);
        }

        private void cbPlumbing3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Plumbing3", ((CheckBox)sender).Checked);
        }

        private void cbHVAC1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("HVAC1", ((CheckBox)sender).Checked);
        }

        private void cbHVAC2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("HVAC2", ((CheckBox)sender).Checked);
        }

        private void cbHVAC3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("HVAC3", ((CheckBox)sender).Checked);
        }

        private void cbElectricity1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Electricity1", ((CheckBox)sender).Checked);
        }

        private void cbElectricity2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Electricity2", ((CheckBox)sender).Checked);
        }

        private void cbElectricity3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Electricity3", ((CheckBox)sender).Checked);
        }

        private void cbPower1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Power1", ((CheckBox)sender).Checked);
        }
        private void cbPower2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Power2", ((CheckBox)sender).Checked);
        }
        private void groupBox5_Enter(object sender, EventArgs e)
        {
        }

        private void cbPower3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Power3", ((CheckBox)sender).Checked);
        }

        private void cbELV1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ELV1", ((CheckBox)sender).Checked);
        }

        private void cbELV2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ELV2", ((CheckBox)sender).Checked);
        }

        private void cbELV3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ELV3", ((CheckBox)sender).Checked);
        }

        private string GetPDFByDWG(string dwgFilePath)
        {
            if(!File.Exists(dwgFilePath))
            {
                return String.Empty;
            }
            FileInfo dwgFile = new FileInfo(dwgFilePath);
            DirectoryInfo dir_displine = dwgFile.Directory;
            DirectoryInfo dir_tz = dir_displine.Parent;
            DirectoryInfo dir_common = dir_tz.Parent;
            Char[] seperator = { '.' };
            String[] file_names = dwgFile.Name.Split(seperator);
            String pdfPath = dir_common.FullName + @"\PDF\" + file_names.First() + ".pdf";
            return pdfPath;
        }

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView.Columns["PDFView"].Index)
            {
                string pdfFilePath = GetPDFByDWG(dataGridView.Rows[e.RowIndex].Cells["FileName"].Value.ToString());
                if (!File.Exists(pdfFilePath))
                {
                    MessageBox.Show("PDF文件不存在！ 路径："+pdfFilePath);
                }
                else
                {
                    System.Diagnostics.Process.Start(pdfFilePath);
                }
            }
        }

        private void btn_quickSign_Click(object sender, EventArgs e)
        {
            CommandSign.QuickSignEx();
        }

        private void cb_ProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fatherpath = "";
            foreach (string webPath in Config.ProjectPath)
            {
                DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
                DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
                foreach (DirectoryInfo Dir_Pro in Dir_Pros)
                {
                    if (Dir_Pro.Name == this.cb_ProNo.Text)
                    {
                        fatherpath = webPath;
                    }
                }
            }
            this.cb_SubProNo.Items.Clear();
            this.cb_SubProNo.Text = "";
//            this.cb_Major.Items.Clear();
            DirectoryInfo Dir_Web2 = new DirectoryInfo(fatherpath + this.cb_ProNo.Text + "\\");
            DirectoryInfo[] Dir_Pros2 = Dir_Web2.GetDirectories();
            foreach (DirectoryInfo Dir_Pro in Dir_Pros2)
            {
                this.cb_SubProNo.Items.Add(Dir_Pro.Name);
            }
        }

        private void cb_SubProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
//             string fatherpath = "";
//             foreach (string webPath in Convention.WebDirectorys)
//             {
//                 DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
//                 DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
//                 foreach (DirectoryInfo Dir_Pro in Dir_Pros)
//                 {
//                     if (Dir_Pro.Name == this.cb_ProNo.Text)
//                     {
//                         fatherpath = webPath;
//                     }
//                 }
//             }
//             this.cb_Major.Items.Clear();
//             DirectoryInfo Dir_Web2 = new DirectoryInfo(fatherpath + this.cb_ProNo.Text + "\\" + this.cb_SubProNo.Text + "\\Common\\TZ\\");
//             DirectoryInfo[] Dir_Pros2 = Dir_Web2.GetDirectories();
//             foreach (DirectoryInfo Dir_Pro in Dir_Pros2)
//             {
//                 if (Dir_Pro.Name != "PDF")
//                 {
//                     string major = Dir_Pro.Name;
//                     switch (major)
//                     {
//                         case "JZ":
//                             major = "建筑";
//                             break;
//                         case "JG":
//                             major = "结构";
//                             break;
//                         case "GPS":
//                             major = "给排水";
//                             break;
//                         case "DL":
//                             major = "电力";
//                             break;
//                         case "NT":
//                             major = "暖通";
//                             break;
//                         case "QD":
//                             major = "强电";
//                             break;
//                         case "RD":
//                             major = "弱电";
//                             break;
//                         default:
//                             break;
//                     }
//                     this.cb_Major.Items.Add(major);
//                 }
//             }
        }

       

    }
}
